package com.yehun.annotation;

import com.yehun.config.RedisLock;
import com.yehun.utils.AnnotationUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ShardedJedisPool;

/**
 * 线程同步锁
 */
@Aspect
@Component("syncLockAspect")
public class SyncLockAspect {

    private final static Logger logger = LoggerFactory.getLogger(SyncLockAspect.class);

    private final ShardedJedisPool jedisPool;

    @Autowired
    public SyncLockAspect(ShardedJedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Around("@annotation(com.yehun.annotation.SyncLock)")
    public Object aroundExec(ProceedingJoinPoint point) throws Throwable {
        logger.info("SyncLockAspect.aroundExec() before...");
        SyncLock syncLock = AnnotationUtils.getAnnotation(point, SyncLock.class);
        if (syncLock != null) {
            RedisLock lock = RedisLock.getInstance();
            lock.setJedisCommands(jedisPool.getResource());
            lock.setLockKey(syncLock.key());
            lock.setTimeout(syncLock.timeout());
            try {
                lock.lock();
            } catch (Exception e) {
                logger.error("SyncLockAspect.aroundExec(), 1.Exception, ", e);
            }
            try {
                return point.proceed();
            } finally {
                try {
                    lock.unlock();
                } catch (Exception e) {
                    logger.error("SyncLockAspect.aroundExec(), 2.Exception, ", e);
                }
            }
        }
        logger.info("SyncLockAspect.aroundExec() after...");
        return null;
    }


}
